// 可达480w的qps，但线上获取qps失败
package qps

import (
	"sync/atomic"
	"time"
)

var qpsMap1 = map[string]*QPSCounter1{}

func NewQPSCounter1(key string) (counter *QPSCounter1) {
	var list = make([]QPSLocal, 10)
	//var qps *QPSLocal
	var index int
	for index, _ = range list {
		list[index] = QPSLocal{}
	}

	counter = &QPSCounter1{
		current: 0,
		//lastQps: 0,
		curTime: 0,
		list:    list,
	}
	qpsMap1[key] = counter

	return
}

// 该方法线上使用有问题，基本qps都是0
// 调用间隔时间不大于10秒。在本机测试，可达480w的qps。优化空间：异步写到counter.list里
func (counter *QPSCounter1) UpdateQps(t time.Time) {
	//counter, exist := qpsMap[key]
	//if exist == false {
	//	logUtil.ErrorLog("qps.bll.UpdateQps fail=>key:%v", key)
	//	return
	//}

	var timestamp = t.Unix()
	if counter.curTime != timestamp {
		//每秒只会执行一次。
		counter.mutex.Lock()
		counter.mutex.Unlock()

		//因获取curTime没加锁，所以存在重复判断不相同情况
		if counter.curTime == timestamp {
			counter.Add()
			return
		}

		var curIndex = counter.curTime % 10
		//将上个时间装入
		//counter.lastQps=counter.current
		counter.list[curIndex].Crtime = t
		counter.list[curIndex].Qps = counter.current

		counter.curTime = timestamp
		counter.current = 0 //重置

	} else {
		counter.Add()
	}
}

func (q *QPSCounter1) Add() {
	atomic.AddInt64(&q.current, 1)
}

func GetCounter1(key string) (counter *QPSCounter1, exist bool) {
	counter, exist = qpsMap1[key]
	return
}
